package jd.se.findpw;

import com.alibaba.fastjson.JSON;
import jd.se.common.Result;
import jd.se.common.Utils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

@WebServlet("/findpw")
public class FindpwAPI extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            req.setCharacterEncoding("UTF-8");

            Reader reader = req.getReader();
            CharArrayWriter out = new CharArrayWriter();

            try {
                char[] charBuff = new char[1024];
                int len = -1;

                while ((len = reader.read(charBuff)) != -1) {
                    out.write(charBuff, 0, len);
                }
                out.flush();

                String  json = out.toString();

                FindDto dto = JSON.parseObject(json,FindDto.class);
                boolean che = new checkService().idCHE(dto);
                if(che==false){
                    Utils.outJson(resp,"99");
                }
                String address = new FindpwSer().FindAddress(dto);
                String Pin=achieveCode();
                sendmail(address,Pin);
                Utils.outJson(resp,Pin);
            }finally {
                out.flush();
                out.close();
                reader.close();
            }
        }catch (Exception e){
            Utils.outResult(resp,Result.fail(500,"系统升级中......!"));
        }
    }
    //发送邮件代码
            public  void sendmail(String address,String PIN) throws Exception {

                     Properties prop = new Properties();
                     prop.setProperty("mail.host", "smtp.qq.com");
                     prop.setProperty("mail.transport.protocol", "smtp");
                     prop.setProperty("mail.smtp.auth", "true");
                     //使用JavaMail发送邮件的5个步骤
                     //1、创建session
                     Session session = Session.getInstance(prop);
                     //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
                     session.setDebug(true);
                     //2、通过session得到transport对象
                     Transport ts = session.getTransport();
                     //3、连上邮件服务器.使用邮箱的用户名和密码连上邮件服务器，发送邮件时，
                // 发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人
                     ts.connect("smtp.qq.com", "1073721275@qq.com", "gtdnogcttskbbcaa");
                     //4、创建邮件
                     Message message = createMail(session,address,PIN);
                     //5、发送邮件
                     ts.sendMessage(message, message.getAllRecipients());
                     ts.close();
                 }
       public static MimeMessage createMail(Session session,String address, String code) throws Exception {
                       //创建邮件对象
                       MimeMessage message = new MimeMessage(session);
                       //指明邮件的发件人
                       message.setFrom(new InternetAddress("1073721275@qq.com"));
                       //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
                       message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
                       //邮件的标题
                       message.setSubject("您的验证码");
                       //邮件的文本内容

                       message.setContent(code, "text/html;charset=UTF-8");
                       //返回创建好的邮件对象
                       return message;
                   }
    // 随机验证码
    public static String achieveCode() {  //由于数字 1 、 0 和字母 O 、l 有时分不清楚，所以，没有数字 1 、 0
        String[] beforeShuffle= new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
                "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
                "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z" };
        List list = Arrays.asList(beforeShuffle);//将数组转换为集合
        Collections.shuffle(list);  //打乱集合顺序
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)); //将集合转化为字符串
        }
        return sb.toString().substring(3, 8);  //截取字符串第4到8
    }
}
